<?php
class helper_setting extends system_view_helper_abstract {
	
	protected $_name = 'setting';
	protected $_data = array();
	protected $_index = null;
	
	/**
	 * @return helper_setting
	 */
	public function setting($index = null) {
		$this->_index = $index;
		if(empty($this->_data)) {
			$lang = system_nav_language::getInstance()->getName();
			$cache = system_cache::factory();
			$name = $this->_name . '.' . $lang;
			if(!($this->_data = $cache->load($name))) {
				$result = array();
				foreach(system_db::getAdapter()->fetchAll("SELECT `name`, `value` FROM `system_setting` WHERE `lang` = '$lang'") as $row) {
					$result[strtolower($row['name'])] = $row['value'];
				}
				$cache->save($name, $result);
				$this->_data = $result;
			}
		}
		return $this;
	}
	
	public function __toString() {
		$return = $this->get($this->_index);
		return $return ? $return : '';
	}
	
	public function __call($method, array $args) {
		if(preg_match('/^get(\w+?)$/', $method, $matches)) {
			return $this->get($matches[1], '');
		}
		return null;
	}
	
	public function get($name, $defValue = null) {
		if($name === null) return $defValue;
		$name = strtolower($name);
		if(!isset($this->_data[$name])) return $defValue;
		return $this->_data[$name];
	}
}
